<template>
  <div class="student-course">
    <div class="page-header">
      <h2>选课管理</h2>
    </div>

    <!-- 筛选条件 -->
    <el-card class="filter-card" shadow="never">
      <el-form :model="filterForm" :inline="true" class="filter-form">
        <el-form-item label="学期">
          <el-select
            v-model="filterForm.semester"
            placeholder="请选择学期"
            clearable
            style="width: 200px"
            @change="handleFilter"
          >
            <el-option label="2024春季" value="2024春季" />
            <el-option label="2024秋季" value="2024秋季" />
            <el-option label="2025春季" value="2025春季" />
            <el-option label="2025秋季" value="2025秋季" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程类型">
          <el-select
            v-model="filterForm.courseType"
            placeholder="请选择课程类型"
            clearable
            style="width: 150px"
            @change="handleFilter"
          >
            <el-option label="必修" value="必修" />
            <el-option label="选修" value="选修" />
            <el-option label="实践" value="实践" />
            <el-option label="理论" value="理论" />
          </el-select>
        </el-form-item>
        
        <el-form-item label="课程名称">
          <el-input
            v-model="filterForm.courseName"
            placeholder="请输入课程名称"
            clearable
            style="width: 200px"
            @change="handleFilter"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleFilter">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 选课统计 -->
    <el-row :gutter="20" class="stats-overview">
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Reading /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalCourses || 0 }}</div>
              <div class="stat-label">可选课程</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Check /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.selectedCourses || 0 }}</div>
              <div class="stat-label">已选课程</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.totalCredits || 0 }}</div>
              <div class="stat-label">总学分</div>
            </div>
          </div>
        </el-card>
      </el-col>
      
      <el-col :span="6">
        <el-card class="stat-card" shadow="hover">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><TrendCharts /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ courseStats.remainingCredits || 0 }}</div>
              <div class="stat-label">剩余学分</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 可选课程列表 -->
    <el-card class="course-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>可选课程</span>
          <div class="header-actions">
            <el-button type="success" @click="refreshCourses">
              <el-icon><Refresh /></el-icon>
              刷新列表
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="course-content">
        <el-table
          :data="availableCourses"
          v-loading="loading"
          stripe
          border
          style="width: 100%"
        >
          <!-- 确保 prop 与后端 DTO 字段一致 -->
          <el-table-column prop="courseNo" label="课程编号" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="courseType" label="课程类型" width="120">
            <template #default="scope">
              <el-tag :type="getCourseTypeTag(scope.row.courseType)">
                {{ scope.row.courseType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credit" label="学分" width="80" />
          <el-table-column prop="periodTotal" label="总学时" width="100" />
          <el-table-column prop="dept" label="开课院系" width="150" />
          <el-table-column prop="teacherName" label="授课教师" width="120" />
          <el-table-column prop="capacity" label="容量" width="80" />
          <el-table-column prop="selected" label="已选" width="80" />
          <el-table-column prop="remaining" label="剩余" width="80" />
          <el-table-column label="操作" width="200" fixed="right" align="center">
            <template #default="scope">
              <div style="display: flex; gap: 8px; justify-content: center;">
                <el-button
                  v-if="!scope.row.isSelected"
                  type="primary"
                  size="small"
                  :disabled="scope.row.remaining <= 0"
                  @click="handleSelectCourse(scope.row)"
                >
                  选课
                </el-button>
                <el-button
                  v-else
                  type="danger"
                  size="small"
                  @click="handleDropCourse(scope.row)"
                >
                  退课
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="handleViewDetail(scope.row)"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 已选课程列表 -->
    <el-card class="selected-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>已选课程</span>
          <div class="header-actions">
            <el-button type="warning" @click="exportSelectedCourses">
              <el-icon><Download /></el-icon>
              导出课表
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="selected-content">
        <el-table
          :data="selectedCourses"
          v-loading="selectedLoading"
          stripe
          border
          style="width: 100%"
        >
          <!-- 确保 prop 与后端 DTO 字段一致 -->
          <el-table-column prop="courseNo" label="课程编号" width="120" />
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="courseType" label="课程类型" width="120">
            <template #default="scope">
              <el-tag :type="getCourseTypeTag(scope.row.courseType)">
                {{ scope.row.courseType }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="credit" label="学分" width="80" />
          <el-table-column prop="periodTotal" label="总学时" width="100" />
          <el-table-column prop="dept" label="开课院系" width="150" />
          <el-table-column prop="teacherName" label="授课教师" width="120" />
          <el-table-column prop="selectTime" label="选课时间" width="160" />
          <el-table-column label="操作" width="180" fixed="right" align="center">
            <template #default="scope">
              <div style="display: flex; gap: 8px; justify-content: center;">
                <el-button
                  type="danger"
                  size="small"
                  @click="handleDropCourse(scope.row)"
                >
                  退课
                </el-button>
                <el-button
                  type="info"
                  size="small"
                  @click="handleViewDetail(scope.row)"
                >
                  详情
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="课程详情"
      width="600px"
    >
      <div class="course-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="课程编号">
            {{ courseDetail.courseNo }}
          </el-descriptions-item>
          <el-descriptions-item label="课程名称">
            {{ courseDetail.courseName }}
          </el-descriptions-item>
          <el-descriptions-item label="课程类型">
            <el-tag :type="getCourseTypeTag(courseDetail.courseType)">
              {{ courseDetail.courseType }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="学分">
            {{ courseDetail.credit }}
          </el-descriptions-item>
          <el-descriptions-item label="总学时">
            {{ courseDetail.periodTotal }}
          </el-descriptions-item>
          <el-descriptions-item label="开课院系">
            {{ courseDetail.dept }}
          </el-descriptions-item>
          <el-descriptions-item label="授课教师">
            {{ courseDetail.teacherName }}
          </el-descriptions-item>
          <el-descriptions-item label="课程容量">
            {{ courseDetail.capacity }}
          </el-descriptions-item>
          <el-descriptions-item label="已选人数">
            {{ courseDetail.selected }}
          </el-descriptions-item>
          <el-descriptions-item label="剩余名额">
            {{ courseDetail.remaining }}
          </el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">
            {{ courseDetail.courseRemark || '无' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, Download, Reading, Check, Star, TrendCharts } from '@element-plus/icons-vue'
// 引入修改后的 API 函数
import { getAvailableCourses, getSelectedCourses, selectCourse, dropCourse } from '../api/studentUser'

// 筛选表单
const filterForm = reactive({
  semester: '2024春季',  // ✅ 修复：改为与数据库一致的格式
  courseType: '',
  courseName: ''
})

// 加载状态
const loading = ref(false)
const selectedLoading = ref(false)

// 课程统计数据
const courseStats = ref({
  totalCourses: 0,
  selectedCourses: 0,
  totalCredits: 0,
  remainingCredits: 0
})

// 可选课程列表
const availableCourses = ref([])

// 已选课程列表
const selectedCourses = ref([])

// 详情对话框
const detailDialogVisible = ref(false)
const courseDetail = ref({})

// 获取课程类型标签
const getCourseTypeTag = (type) => {
  const typeMap = {
    '必修': 'primary',
    '选修': 'success',
    '实践': 'warning',
    '理论': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取可选课程列表
const fetchAvailableCourses = async () => {
  loading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    if (!user.studentId) {
      ElMessage.error('请先登录')
      return
    }

    console.log('📚 获取可选课程 - studentId:', user.studentId, 'semester:', filterForm.semester)
    
    // 调用正确的 API，传递 studentId 和 semester
    const response = await getAvailableCourses(user.studentId, filterForm.semester)
    console.log('📚 API响应:', response)
    
    // ✅ 修复：后端返回的是直接的课程列表，不是分页对象
    if (response && response.data) {
      // 后端返回的 data 直接就是课程列表数组
      availableCourses.value = Array.isArray(response.data) ? response.data : []
      courseStats.value.totalCourses = availableCourses.value.length
      console.log('✅ 可选课程数量:', availableCourses.value.length)
    } else {
      availableCourses.value = []
      courseStats.value.totalCourses = 0
      console.log('⚠️ 无数据返回')
    }
    
  } catch (error) {
    console.error('获取可选课程失败:', error)
    // 如果真实请求失败，显示模拟数据（用于调试）
    availableCourses.value = [
      {
        courseId: 1,
        courseNo: 10001, // 确保字段名与 DTO 一致
        courseName: '高等数学',
        courseType: '必修',
        credit: 4,
        periodTotal: 64,
        dept: '数学学院',
        teacherName: '王老师',
        capacity: 50,
        selected: 30,
        remaining: 20,
        isSelected: false,
        courseRemark: '基础数学课程'
      },
      {
        courseId: 2,
        courseNo: 10002,
        courseName: '大学英语',
        courseType: '必修',
        credit: 3,
        periodTotal: 48,
        dept: '外国语学院',
        teacherName: '李老师',
        capacity: 40,
        selected: 25,
        remaining: 15,
        isSelected: false,
        courseRemark: '英语基础课程'
      },
      {
        courseId: 3,
        courseNo: 10003,
        courseName: '计算机基础',
        courseType: '必修',
        credit: 3,
        periodTotal: 48,
        dept: '计算机学院',
        teacherName: '张老师',
        capacity: 45,
        selected: 35,
        remaining: 10,
        isSelected: false,
        courseRemark: '计算机入门课程'
      },
      {
        courseId: 4,
        courseNo: 10004,
        courseName: '艺术欣赏',
        courseType: '选修',
        credit: 2,
        periodTotal: 32,
        dept: '艺术学院',
        teacherName: '赵老师',
        capacity: 30,
        selected: 15,
        remaining: 15,
        isSelected: false,
        courseRemark: '艺术类选修课程'
      }
    ]
    courseStats.value.totalCourses = availableCourses.value.length
  } finally {
    loading.value = false
  }
}

// 获取已选课程列表
const fetchSelectedCourses = async () => {
  selectedLoading.value = true
  
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    if (!user.studentId) {
      ElMessage.error('请先登录')
      return
    }

    console.log('📖 获取已选课程 - studentId:', user.studentId, 'semester:', filterForm.semester)
    
    // 调用正确的 API，传递 studentId 和 semester
    const response = await getSelectedCourses(user.studentId, filterForm.semester)
    console.log('📖 API响应:', response)
    
    // ✅ 修复：后端返回的是直接的课程列表，不是分页对象
    if (response && response.data) {
      // 后端返回的 data 直接就是课程列表数组
      selectedCourses.value = Array.isArray(response.data) ? response.data : []
      // 更新统计数据
      courseStats.value.selectedCourses = selectedCourses.value.length
      courseStats.value.totalCredits = selectedCourses.value.reduce((sum, course) => sum + (course.credit || 0), 0)
      console.log('✅ 已选课程数量:', selectedCourses.value.length)
    } else {
      selectedCourses.value = []
      courseStats.value.selectedCourses = 0
      courseStats.value.totalCredits = 0
      console.log('⚠️ 无数据返回')
    }
    
  } catch (error) {
    console.error('获取已选课程失败:', error)
    // 如果真实请求失败，显示模拟数据（用于调试）
    selectedCourses.value = [
      {
        courseId: 5,
        courseNo: 10005, // 确保字段名与 DTO 一致
        courseName: '数据结构',
        courseType: '必修',
        credit: 3,
        periodTotal: 48,
        dept: '计算机学院',
        teacherName: '刘老师',
        selectTime: '2024-01-15 10:30:00',
        courseRemark: '计算机专业核心课程'
      }
    ]
    courseStats.value.selectedCourses = 1
    courseStats.value.totalCredits = 3
  } finally {
    selectedLoading.value = false
  }
}

// 选课
const handleSelectCourse = async (course) => {
  try {
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    console.log('🎯 选课请求 - studentId:', user.studentId, 'courseId:', course.courseId, 'semester:', filterForm.semester)
    
    // ✅ 修复：传递 semester 参数
    await selectCourse(user.studentId, course.courseId, filterForm.semester)
    ElMessage.success('选课申请已提交，等待教师审核')
    
    // 刷新列表
    await fetchAvailableCourses()
    await fetchSelectedCourses()
  } catch (error) {
    console.error('选课失败:', error)
    ElMessage.error(error.message || '选课失败，请重试')
  }
}

// 退课
const handleDropCourse = async (course) => {
  try {
    await ElMessageBox.confirm(
      `确定要退选课程 "${course.courseName}" 吗？`,
      '退课确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const user = JSON.parse(localStorage.getItem('user') || '{}')
    await dropCourse(user.studentId, course.courseId)
    ElMessage.success('退课成功')
    // 刷新列表
    await fetchAvailableCourses()
    await fetchSelectedCourses()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退课失败:', error)
      ElMessage.error('退课失败，请重试')
    }
  }
}

// 查看详情
const handleViewDetail = (course) => {
  courseDetail.value = { ...course }
  detailDialogVisible.value = true
}

// 筛选
const handleFilter = () => {
  fetchAvailableCourses()
  fetchSelectedCourses()
}

// 重置筛选
const handleReset = () => {
  filterForm.semester = '2024春季'  // ✅ 修复：改为与数据库一致的格式
  filterForm.courseType = ''
  filterForm.courseName = ''
  fetchAvailableCourses()
  fetchSelectedCourses()
}

// 刷新课程列表
const refreshCourses = () => {
  fetchAvailableCourses()
  fetchSelectedCourses()
}

// 导出已选课程
const exportSelectedCourses = () => {
  ElMessage.success('导出功能开发中...')
}

// 组件挂载时获取数据
onMounted(() => {
  fetchAvailableCourses()
  fetchSelectedCourses()
})
</script>

<style scoped>
.student-course {
  background: #f5f7fa;
  padding: 20px;
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
  box-sizing: border-box;
}

.page-header {
  margin-bottom: 32px;
  text-align: center;
}

.page-header h2 {
  margin: 0;
  color: #2c3e50;
  font-size: 28px;
  font-weight: 600;
  letter-spacing: 1px;
}

.filter-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
}

.filter-card :deep(.el-card__body) {
  padding: 20px;
}

.filter-form {
  margin-bottom: 0;
}

.filter-form :deep(.el-form-item) {
  margin-bottom: 16px;
  margin-right: 24px;
}

.filter-form :deep(.el-form-item__label) {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.stats-overview {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.stat-card :deep(.el-card__body) {
  padding: 20px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: #ffffff;
  font-size: 24px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 32px;
  font-weight: 700;
  color: #2c3e50;
  line-height: 1;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #606266;
  font-weight: 500;
}

.course-card,
.selected-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border: 1px solid #e4e7ed;
  background: #ffffff;
  overflow: hidden;
}

.course-card :deep(.el-card__header),
.selected-card :deep(.el-card__header) {
  background: #f5f7fa;
  border-bottom: 1px solid #ebeef5;
  padding: 16px 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header span {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.header-actions .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.course-content,
.selected-content {
  padding: 0;
}

.course-content :deep(.el-table),
.selected-content :deep(.el-table) {
  border-radius: 0;
}

.course-content :deep(.el-table__header),
.selected-content :deep(.el-table__header) {
  background: #f5f7fa;
}

.course-content :deep(.el-table th),
.selected-content :deep(.el-table th) {
  background: transparent;
  color: #2c3e50;
  font-weight: 600;
  font-size: 14px;
  border-bottom: 1px solid #ebeef5;
  padding: 12px;
}

.course-content :deep(.el-table td),
.selected-content :deep(.el-table td) {
  padding: 12px;
  border-bottom: 1px solid #ebeef5;
  color: #606266;
  font-size: 14px;
}

.course-content :deep(.el-table__row:hover),
.selected-content :deep(.el-table__row:hover) {
  background: #f5f7fa;
}

.course-content :deep(.el-table__row:nth-child(even)),
.selected-content :deep(.el-table__row:nth-child(even)) {
  background: #fafafa;
}

.course-content :deep(.el-table__row:nth-child(even):hover),
.selected-content :deep(.el-table__row:nth-child(even):hover) {
  background: #f5f7fa;
}

.course-content :deep(.el-button),
.selected-content :deep(.el-button) {
  border-radius: 4px;
  font-weight: 500;
  padding: 6px 12px;
  font-size: 12px;
  transition: all 0.3s ease;
}

/* 课程详情样式 */
.course-detail {
  padding: 20px 0;
}

.course-detail :deep(.el-descriptions) {
  border-radius: 8px;
  overflow: hidden;
}

.course-detail :deep(.el-descriptions__header) {
  background: #f5f7fa;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

.course-detail :deep(.el-descriptions__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

.course-detail :deep(.el-descriptions__body) {
  background: #ffffff;
}

.course-detail :deep(.el-descriptions-item__label) {
  background: #fafafa;
  color: #606266;
  font-weight: 600;
  width: 120px;
}

.course-detail :deep(.el-descriptions-item__content) {
  color: #2c3e50;
  padding: 12px 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding-top: 16px;
}

.dialog-footer .el-button {
  border-radius: 4px;
  font-weight: 500;
  padding: 10px 20px;
  transition: all 0.3s ease;
}

/* 对话框样式优化 */
:deep(.el-dialog) {
  border-radius: 8px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  border: 1px solid #e4e7ed;
}

:deep(.el-dialog__header) {
  background: #f5f7fa;
  border-radius: 8px 8px 0 0;
  padding: 16px 20px;
  border-bottom: 1px solid #ebeef5;
}

:deep(.el-dialog__title) {
  color: #2c3e50;
  font-weight: 600;
  font-size: 16px;
}

:deep(.el-dialog__body) {
  padding: 20px;
}

:deep(.el-dialog__footer) {
  padding: 16px 20px;
  background: #f5f7fa;
  border-radius: 0 0 8px 8px;
  border-top: 1px solid #ebeef5;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-course {
    padding: 16px;
  }
  
  .page-header h2 {
    font-size: 24px;
  }
  
  .stats-overview {
    margin-bottom: 16px;
  }
  
  .stat-content {
    flex-direction: column;
    text-align: center;
    gap: 12px;
  }
  
  .stat-icon {
    width: 50px;
    height: 50px;
    font-size: 20px;
  }
  
  .stat-value {
    font-size: 24px;
  }
  
  .filter-form :deep(.el-form-item) {
    margin-right: 0;
    width: 100%;
  }
  
  .filter-form :deep(.el-input),
  .filter-form :deep(.el-select) {
    width: 100%;
  }
}

@media (max-width: 480px) {
  .student-course {
    padding: 12px;
  }
  
  .page-header h2 {
    font-size: 20px;
  }
  
  .filter-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .stat-card :deep(.el-card__body) {
    padding: 16px;
  }
  
  .stat-icon {
    width: 40px;
    height: 40px;
    font-size: 18px;
  }
  
  .stat-value {
    font-size: 20px;
  }
  
  .course-content :deep(.el-table th),
  .course-content :deep(.el-table td),
  .selected-content :deep(.el-table th),
  .selected-content :deep(.el-table td) {
    padding: 12px 8px;
    font-size: 13px;
  }
}
</style>